// MainDlg.h : interface of the CMainDlg class
//
/////////////////////////////////////////////////////////////////////////////

#pragma once

#include <locale.h>

#include "include/LuoSnapShot.h"

extern LuoSnapShot::UActivator * g_pLuoSnapShot;

class CMainDlg : public CDialogImpl<CMainDlg>, public CUpdateUI<CMainDlg>,
		public CMessageFilter, public CIdleHandler
{
	int count;
public:
	enum { IDD = IDD_MAINDLG };

	virtual BOOL PreTranslateMessage(MSG* pMsg)
	{
		return CWindow::IsDialogMessage(pMsg);
	}

	virtual BOOL OnIdle()
	{
		return FALSE;
	}

	BEGIN_UPDATE_UI_MAP(CMainDlg)
	END_UPDATE_UI_MAP()

	BEGIN_MSG_MAP(CMainDlg)
		MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
		MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
		COMMAND_ID_HANDLER(ID_APP_ABOUT, OnAppAbout)
		COMMAND_ID_HANDLER(IDOK, OnOK)
		COMMAND_ID_HANDLER(IDCANCEL, OnCancel)

		MESSAGE_HANDLER(LuoSnapShot::WM_LUO_SNAPSHOT_CALLBACK, OnLuoSnapShotCallback)

	END_MSG_MAP()

// Handler prototypes (uncomment arguments if needed):
//	LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
//	LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
//	LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)

	LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		// center the dialog on the screen
		CenterWindow();

		// set icons
		HICON hIcon = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
			IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR);
		SetIcon(hIcon, TRUE);
		HICON hIconSmall = (HICON)::LoadImage(_Module.GetResourceInstance(), MAKEINTRESOURCE(IDR_MAINFRAME), 
			IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR);
		SetIcon(hIconSmall, FALSE);

		// register object for message filtering and idle updates
		CMessageLoop* pLoop = _Module.GetMessageLoop();
		ATLASSERT(pLoop != NULL);
		pLoop->AddMessageFilter(this);
		pLoop->AddIdleHandler(this);

		UIAddChildWindowContainer(m_hWnd);

		count = 1;
		
		// test url
		wchar_t url[MAX_PATH] = {0, };
		wsprintf(url, L"http://www.cppblog.com/kesalin/");
		SetDlgItemText(IDC_URL, url);

		return TRUE;
	}

	LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
	{
		// unregister message filtering and idle updates
		CMessageLoop* pLoop = _Module.GetMessageLoop();
		ATLASSERT(pLoop != NULL);
		pLoop->RemoveMessageFilter(this);
		pLoop->RemoveIdleHandler(this);

		return 0;
	}

	LRESULT OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		CAboutDlg dlg;
		dlg.DoModal();
		return 0;
	}

	LRESULT OnCancel(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		CloseDialog(wID);
		return 0;
	}

	void CloseDialog(int nVal)
	{
		DestroyWindow();
		::PostQuitMessage(nVal);
	}

	//////////////////////////////////////////////////////////////////////////

	LRESULT OnOK(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
	{
		// TODO: Add validation code 
		//CloseDialog(wID);

		wchar_t timeString[MAX_PATH];
		getTimeString(timeString);

		wchar_t savePath[MAX_PATH];
		GetModuleFileNameW(0, savePath, MAX_PATH);
		PathRemoveFileSpecW(savePath);
		wsprintf(savePath, L"%s\\%s.png", savePath, timeString);

		wchar_t url[MAX_PATH] = {0, };
		GetDlgItemText(IDC_URL, url, MAX_PATH);

		// Create a locale object representing the English locale
		_locale_t locale = _create_locale(LC_ALL, "English");

		if (wcslen(url) > 7 && _wcsnicmp_l(url, L"http://", 7, locale) == 0){
			capture(url, savePath);
		}
		else {
			::MessageBoxW(*this, L"Url Format error!", L"Error", MB_OK);
		}
		return 0;
	}

	LRESULT OnLuoSnapShotCallback(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
	{
		int cookie = (int)wParam;
		HRESULT hResult = (HRESULT)lParam;

		wchar_t info[MAX_PATH] = {0, };
		if (hResult == S_OK){
			wsprintf(info, L"Snap shot %d is succeed!\n", cookie);
			OutputDebugStringW(info);
		}
		else {
			wsprintf(info, L"Snap shot %d is failed!\n", cookie);
			OutputDebugStringW(info);
		}
		return 0;
	}

	void capture(const LPCWSTR url, const LPCWSTR savePath)
	{
		if (g_pLuoSnapShot) {
			LuoSnapShot::WebItem item;
			item.Uri = url;
			item.Path = savePath;
			item.Show = true;

			item.ImageWidth = 640;
			item.ImageHeight = 480;

			item.Target = *this;
			item.Message = LuoSnapShot::WM_LUO_SNAPSHOT_CALLBACK;
			item.Cookie = ++count;

			item.PageWidth = 1024;
			item.PageHeight = 768;

			item.ShotDelay = 2 * 1000;
			item.NavigateTimeout = 20 * 1000;

			g_pLuoSnapShot->AddWebItem(&item);
		}
	}

	void getTimeString(wchar_t*string)
	{
		if (string == NULL){
			return ;
		}

		static const wchar_t* s_month[] = {
			L"Jan", L"Feb", L"Mar", L"Apr", L"May", L"Jun", L"Jul", L"Aug", L"Sep", L"Oct", L"Nov", L"Dec"
		};

		wchar_t* str = NULL;
		wchar_t buf[MAX_PATH] = {0, };
		wsprintf(buf, L"%S", __DATE__);

		wchar_t separater[5];
		separater[0] = L'\"';
		separater[1] = L' ';
		separater[2] = L'\n';
		separater[3] = L':';
		separater[4] = 0x00;

		wchar_t* next = NULL;
		str = wcstok_s(buf,separater, &next);

		int month = 1;

		//"Nov 27 2008"
		int i;
		for(i = 0; i < 12; i++){
			if(wcsncmp(s_month[i], str, 3) == 0){
				month = i + 1;
				break;
			}
		}

		str = (wchar_t *)wcstok_s(NULL,separater,&next);
		int day = _wtoi(str);

		str = (wchar_t *)wcstok_s(NULL,separater,&next);
		int year = _wtoi(str);

		wsprintf(buf, L"%S", __TIME__);
		next = NULL;
		str = wcstok_s(buf,separater, &next);
		int hour = _wtoi(str);

		str = wcstok_s(NULL,separater, &next);
		int minute = _wtoi(str);

		str = wcstok_s(NULL,separater, &next);
		int second = _wtoi(str);

		wsprintf(string, L"%04d%02d%02d%02d%02d%02d", year, month, day, hour, minute, second);
	}
};
